
import requests
from config.cfg import *
from pprint import pprint


class SClass:

    def _printResponse(self, response):
        print('\n\n-------- HTTP response * begin -------')
        print(response.status_code)

        for k, v in response.headers.items():
            print(f'{k}: {v}')

        print('')

        body = response.content.decode('utf8')
        print(body)

        try:
            jsonBody = response.json()
            print(f'\n\n---- 消息体json ----\n')
            pprint(jsonBody)
        except:
            print('消息体不是json格式！！')

        print('-------- HTTP response * end -------\n\n')

    # 列出班级
    def list_class(self, gradeid=None):
        params = {
            'vcode': g_code,
            'action': "list_classes_by_schoolgrade"
        }

        if gradeid:
            params['gradeid'] = gradeid

        res = requests.get(url=g_api_url_class, params=params)

        self._printResponse(res)

        return res

    # 添加班级
    def add_class(self, gradeid, name, studentlimit):
        data = {
            "vcode": g_code,
            "action": "add",
            "grade": gradeid,
            "name": name,
            "studentlimit": studentlimit
        }

        res = requests.post(url=g_api_url_class, data=data)

        self._printResponse(res)

        return res

    # 删除班级
    def delete_class(self, classid):
        url = f'{g_api_url_class}/{classid}'
        data = {
            "vcode": g_code
        }

        res = requests.delete(url=url, data=data)

        self._printResponse(res)

        return res

    # 删除所有班级
    def delete_all_class(self):
        res = self.list_class()
        resObj = res.json()

        for one in resObj['retlist']:
            self.delete_class(classid=one['id'])

    # 修改班级
    def modify_class(self, classid, name, studentlimit):
        url = f"{g_api_url_class}/{classid}"
        data = {
            "vcode": g_code,
            "action": "modify",
            "name": name,
            "studentlimit": studentlimit
        }

        res = requests.put(url=url, data=data)

        self._printResponse(res)

        return res


scm = SClass()

if __name__ == '__main__':
    # scm.add_class(gradeid=1, name="七2班", studentlimit=60)
    # scm.delete_class(classid=20247)
    # scm.modify_class(classid=20248, name="七二班", studentlimit=66)
    scm.delete_all_class()
    scm.list_class()

